import time

from selenium.webdriver.chrome import webdriver
from selenium.webdriver.common import alert
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

from common.dolog import DoLog

dl = DoLog()
myLogger=dl.getLogger(__name__)

class BasePage():
    eloginOrUname = (By.XPATH,"//*[@id='ECS_MEMBERZONE']/a[1]")
    # 初始化
    def __init__(self,driver=None):
        # self.driver = webdriver.WebDriver()
        # self.driver.get('http://192.168.109.131/user.php')
        # self.driver.maximize_window()
        # self.loger=DoLog().getLogger(__name__)
        if driver is None:
            self.driver = webdriver.WebDriver()
            # 获取网页
            self.driver.get("http://192.168.109.131/")
            self.driver.maximize_window()
            self.driver.implicitly_wait(10)
            time.sleep(2)
        else:
            self.driver = driver

    # 定位元素
    def findEle(self,locator):
        try:

            ele = WebDriverWait(self.driver,10,1).\
                until(lambda d:d.find_element(*locator))
            myLogger.info('开始查找元素')
        except Exception as e:
            myLogger.info(f'查找元素发生异常{locator},异常信息{e}')
        else:
            myLogger.info(f'元素找到了{locator}')
            return ele
        finally:
            myLogger.info(f'差找完成{locator}')

    # 向元素中输入内容
    def inpuText(self,ele,msg):
        try:
            ele.send_keys(msg)
            myLogger.info('向元素中输入内容')
        except Exception as e:
            myLogger.info(f'查找元素发生异常{ele},异常信息{e}')
        else:
            myLogger.info(f'元素找到了{ele}')
            return ele
        finally:
            myLogger.info(f'差找完成{ele}')

    # 点击选中元素
    def eleClick(self,ele):
        try:
            ele.click()
            myLogger.info('点击选中元素')
        except Exception as e:
            myLogger.info(f'点击选中元素发生异常{ele},异常信息{e}')
        else:
            myLogger.info(f'点击成功{ele}')
            return ele
        finally:
            myLogger.info(f'完成{ele}')
    # 获取元素的文本
    def getEleTxt(self, ele):
        try:

            eleTxt = ele.text
            myLogger.info("获取元素的文本")
        except Exception as e:
            myLogger.info(f"获取元素的文本发生异常{ele},异常信息{e}" )
        else:
            myLogger.info(f"获取元素的文本成功{ele}")
            return eleTxt
        finally:
            myLogger.info(f"获取元素的文本完成{ele}")
    # 获取弹窗的文本
    def getAlertTxt(self):
        try:
            print('获取弹窗的文本~~~~~')
            alert: Alert = self.driver.switch_to.alert
            t = alert.text
            alert.accept()
        except Exception as e:
            myLogger.info(f'获取弹窗的文本发生异常,异常信息{e}')
        else:
            myLogger.info(f'获取弹窗的文本成功~~~~~~~~~')
            return t
        finally:
            myLogger.info(f'获取弹窗的文本完成~~~~~')


